package com.cpr.demo.config;

import cn.hutool.core.util.RandomUtil;
import com.cpr.demo.constant.RedisKeyConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.Duration;

/**
 * @author Chen Panrui
 * created at 2021/10/9 17:36
 */
@Configuration
@Slf4j
public class MqConfig {

    @Value("${app.mynode}")
    private String node;
    @Value("${spring.redis.timeout}")
    private Duration timeout;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Bean
    String serverId(){
        String serverId = String.format("%s:%s", node, RandomUtil.randomInt(1000, 9999));
        // 每个应用 启动的时候 往 groups键里面放 当前的serverId
        stringRedisTemplate.boundListOps(RedisKeyConstant.MQ_MULTI_GROUPS).leftPush(serverId);
        return serverId;
    }

    @Bean
    Long mqMaxHold(){
        // 需要 redis.brpop()的最大等待时间 < redis.timeout的时间
        long seconds = timeout.getSeconds();
        return seconds-1L;
    }
}
